/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * This file is part of retabel.
 *
 * Copyright (c) 2011 by individual contributors as indicated by the
 * @author tags. See the copyright.txt file in the distribution
 * for a full listing of individual contributors.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */

package org.retabel.backendbean;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.message.BasicNameValuePair;
import org.apache.myfaces.component.html.ext.HtmlDataTable;
import org.retabel.jsf.ConfigSetUriBuilder;
import org.retabel.jsf.PagedListDataModel;
import org.retabel.ui.ConfigAttributeUI;
import org.retabel.ui.ConfigSetUI;
import org.retabel.util.HttpGetClientRequestRunner;
import org.retabel.util.HttpPutClientRequestRunner;
import org.retabel.util.JaxbUtils;
import org.retabel.util.LogLines;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xsd.configset.ConfigAttribute;
import xsd.configset.ConfigSet;
import xsd.configset.ConfigSets;

import javax.enterprise.context.RequestScoped;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.component.UIData;
import javax.faces.context.FacesContext;
import javax.faces.model.ArrayDataModel;
import javax.faces.model.DataModel;
import javax.inject.Named;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@ManagedBean
@RequestScoped
@Named
public class ConfigSetListBean extends PagedListBean {

    // constants

    private static final Logger log = LoggerFactory.getLogger(ConfigSetListBean.class);

    // private fields

    private LogLines logLines = new LogLines(log);

    private UIData uiAttributeData = new HtmlDataTable();

    // private functions

    private ConfigSets getPage(int first, int maxRows) throws Exception {
        // we don't want any log lines, use null as log lines parameter therefore
        return new HttpGetClientRequestRunner<ConfigSets>(null) {
            @Override
            protected ConfigSets onSuccess(HttpResponse response, LogLines logLines) throws Exception {
                return JaxbUtils.unmarshal(ConfigSetUriBuilder.getConfigSetsXmlSchemaURI().toURL(),
                                           response.getEntity().getContent(), ConfigSets.class);
            }

            @Override
            protected void onFailure(HttpResponse response, LogLines logLines) throws Exception {
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,
                                                                                    "request failed",
                                                                                    response.getStatusLine().toString()));
            }
        }.run(ConfigSetUriBuilder.getConfigSetsURI(first, maxRows));
    }

    private ConfigSetUI getConfigSetUI(ConfigSet configSet) {
        ConfigSetUI configSetUI = new ConfigSetUI();

        configSetUI.setName(configSet.getName());

        if (configSet.getAttributes() != null) {
            for (ConfigAttribute configAttribute : configSet.getAttributes().getAttribute()) {
                ConfigAttributeUI configAttributeUI = new ConfigAttributeUI();
                configAttributeUI.setName(configAttribute.getName());
                configAttributeUI.setType(configAttribute.getType());
                configAttributeUI.setValue(configAttribute.getValue());

                configSetUI.getConfigAttributes().add(configAttributeUI);
            }
        }
        return configSetUI;
    }

    // protected methods

    @Override
    protected DataModel getDataModel() throws Exception {
        ConfigSets configSets = getPage(getUiData().getFirst(), getUiData().getRows());

        List<ConfigSetUI> configSetUIs = new ArrayList<>();
        int count = 0;

        if (configSets != null && configSets.getList() != null) {
            count = configSets.getCount();

            for (ConfigSet configSet : configSets.getList().getConfigSet()) {
                ConfigSetUI configSetUI = getConfigSetUI(configSet);

                configSetUIs.add(configSetUI);
            }
        }

        return new PagedListDataModel(configSetUIs, count, getUiData().getRows());
    }

    public DataModel getAttributeDataModel() throws Exception {
        String name = getName();

        if (StringUtils.isNotBlank(name)) {
            // we don't want any log lines, use null as log lines parameter therefore
            ConfigSet configSet = new HttpGetClientRequestRunner<ConfigSet>(null) {
                @Override
                protected ConfigSet onSuccess(HttpResponse response, LogLines logLines) throws Exception {
                    return JaxbUtils.unmarshal(ConfigSetUriBuilder.getConfigSetsXmlSchemaURI().toURL(),
                                               response.getEntity().getContent(), ConfigSet.class);
                }

                @Override
                protected void onFailure(HttpResponse response, LogLines logLines) throws Exception {
                    FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,
                                                                                        "request failed",
                                                                                        response.getStatusLine().toString()));
                }
            }.run(ConfigSetUriBuilder.getConfigSetURI(name));

            ConfigSetUI configSetUI = getConfigSetUI(configSet);

            return new ArrayDataModel(configSetUI.getConfigAttributes().toArray(new ConfigAttributeUI[0]));
        }

        return new ArrayDataModel();
    }

    // public functions

    @Override
    protected void delete() throws Exception {
        // deleting config sets isn't allowed
        throw new UnsupportedOperationException();
    }

    public void edit() throws Exception {
        // do nothing
    }

    public void save() throws Exception {
        final ConfigAttributeUI configAttributeUI = (ConfigAttributeUI) uiAttributeData.getRowData();

        //ArrayDataModel dataModel = (ArrayDataModel) uiAttributeData.getValue();
        //ConfigAttributeUI[] configAttributeUIs = (ConfigAttributeUI[]) dataModel.getWrappedData();

        //for (final ConfigAttributeUI configAttributeUI : configAttributeUIs) {
        new HttpPutClientRequestRunner<Boolean>(logLines) {
            @Override
            protected HttpEntity getHttpEntity() throws Exception {
                List<NameValuePair> formparams = new ArrayList<>();

                formparams.add(new BasicNameValuePair("value", configAttributeUI.getValue()));

                return new UrlEncodedFormEntity(formparams, "UTF-8");
            }

            @Override
            protected Boolean onSuccess(HttpResponse response, LogLines logLines) throws Exception {
                logLines.log(getResponseContentAsString(response));

                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("updated successfully"));

                return Boolean.TRUE;
            }

            @Override
            protected void onFailure(HttpResponse response, LogLines logLines) throws Exception {
                logLines.log(getResponseContentAsString(response));

                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "update failed",
                                                                                    response.getStatusLine().toString()));
            }
        }.run(ConfigSetUriBuilder.getConfigAttributeUpdateURI(getName(), configAttributeUI.getName()));
        //}
    }

    // beans

    /**
     * Gets the attribute table data model
     *
     * @return the attribute data model
     * @throws Exception
     */
    public DataModel getAttributeTableModel() throws Exception {
        return getAttributeDataModel();
    }

    /**
     * Gets the uiAttributeData.
     *
     * @return The uiAttributeData value.
     */
    public UIData getUiAttributeData() {
        return uiAttributeData;
    }

    /**
     * Sets the uiAttributeData.
     *
     * @param newUiAttributeData The uiAttributeData value to set.
     */
    public void setUiAttributeData(UIData newUiAttributeData) {
        this.uiAttributeData = newUiAttributeData;
    }

    /**
     * Gets the logLines.
     *
     * @return The logLines value.
     */
    public List<LogLines.LogLine> getAttributeLogLines() {
        return logLines.getLogLines();
    }

    /**
     * Gets the name request parameter
     *
     * @return the name request parameter
     */
    public String getName() {
        Map<String, String> params = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
        return params.get("name");
    }

}